#include <_ez80F91.h>
#include "ZSysgen.h"
#include "ZTypes.h"
#include "ZInterrupt.h"

#include "Types.h"
#include "sleep.h"

// keeps track of milliseconds past while timer is running
unsigned int count;

/*
 * Initialize the timer used for sleeping
 * Should be called on startup
 *
 * Params:
 *		none
 *
 * Returns:
 *		none
 */
void sleepInit()
{
	UINT16 rr_val;

	TMR3_CTL = 0x00;
	// register timer interrupt handler
	RZKInstallInterruptHandler(tmr3_isr, IV_TMR3);

	// set the timeout to 1 ms
	rr_val = (UINT16)(((TICKS_PER_SECOND / 1000) * 1) / 16);
	TMR3_RR_L = (UINT8)(rr_val & 0x00FF);
	TMR3_RR_H = (UINT8)((rr_val & 0xFF00) >> 8);

	// enable timer, continuous mode, clock diver = 16
	TMR3_CTL = 0x0C;
	// enable timer interrupt
	TMR3_IER = 0x01;
}

/*
 * Sleep for the number of milliseconds passed in
 * NOTE: this function is not thread safe unless
 *       you ensure nothing can preempt this function
 *
 * Params:
 *		ms - number of milliseconds to sleep
 *
 * Returns:
 *		none
 */
void sleep(unsigned int ms)
{
	count = 0;
	// turn on TMR3
	TMR3_CTL |= 0x01;
	// sleep
	while (count < ms) ;
	// disable timer
	TMR3_CTL &= 0xFE;
}

/*
 * Sleep timer interrupt handler
 *
 * Params:
 *		none
 *
 * Returns:
 *		none
 */
void interrupt tmr3_isr()
{
	UINT8 tmp;
	// clear timer interrupt
	tmp = TMR3_IIR;
	count++;
}

